package enterprise.manage.dao;

import enterprise.manage.entity.Orders;
import enterprise.manage.entity.Stocks;
import org.apache.commons.lang.StringUtils;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.HibernateDao;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User:zhenmingyue
 * Date: 2012-11-20
 * Desc:
 */
@Repository
@Transactional
public class StockDao extends HibernateDao<Stocks, Long> {

/**
     * @param pageNo
     * @param pageSize
     * @param queryBegin
     * @param queryEnd
     * @param stockNo
     * @return
     */
    @SuppressWarnings("unchecked")
    public Page<Stocks> getStockPage(int pageNo, int pageSize, Calendar queryBegin, Calendar queryEnd,
                                     String inOrOut, String stockNo, String purchaseNo, String productType
                                     ) {
        Criteria criteria = this.getSession().createCriteria(Stocks.class);
        criteria.setCacheable(true);
        criteria.setCacheMode(CacheMode.GET);
        criteria.setCacheRegion("defaultCache");
        String queryTimeTypeName = "createTime";


        if (queryBegin != null) {
            criteria.add(Restrictions.ge(queryTimeTypeName, queryBegin));
        }
        if (queryEnd != null) {
            criteria.add(Restrictions.lt(queryTimeTypeName, queryEnd));
        }
        if (StringUtils.isNotBlank(productType)) {
            criteria.createCriteria("product").add(Restrictions.eq("type", productType));
        }
        if (StringUtils.isNotBlank(stockNo)) {
            criteria.add(Restrictions.eq("stockNo", stockNo));
        }
        if (StringUtils.isNotBlank(purchaseNo)) {
            criteria.createCriteria("purchase").add(Restrictions.like("purchaseNo", purchaseNo, MatchMode.START));
        }
        if (StringUtils.isNotBlank(inOrOut)) {
            criteria.add(Restrictions.like("inOrOut", inOrOut, MatchMode.ANYWHERE));
        }
        criteria.addOrder(Order.desc(queryTimeTypeName));
        List result = criteria.list();
        Page<Stocks> page = new Page<Stocks>();
        if (page.isAutoCount()) {
            int totalCount = countCriteriaResult(criteria);
            page.setTotalCount(totalCount);
        }
        page.setOrderBy(queryTimeTypeName);
        page.setOrder("desc");
        page.setPageSize(pageSize);
        page.setPageNo(pageNo);
        setPageParameter(criteria, page);

        page.setResult(result);
        return page;
    }
}
